<?php
namespace app\common\controller;
use app\common\model\Access;
use app\common\model\Group;
use app\common\model\Rule;
use think\Session;
use think\Request;

class Auth
{
     /**
	 * 判断是否存在权限
	 */
	 public static function is_auth($admin_id,$auth)
	 {
		$agid = (new Access())->getAccessArr(['admin_id'=>$admin_id],'agid');
		$rules = (new Group())->groupFieldList($agid,'rules');
		if(in_array('*',$rules))
		{
			return true;
		}
		$arid = [];
		foreach($rules as $vo)
		{
			$arid = array_merge($arid,explode(',',$vo));
		}
		$arid = array_unique($arid);
		$columns = (new Rule())->columns($arid,$auth);
		$count = count($columns);
		if($count > 0)
		{
			$type = [];
			foreach($columns as $vo)
			{
				if(!$vo['param'])
				{
					return true;
				}
				$type[] = $vo['param'];
			}
			$info = Request::instance()->param();
			if(in_array($info['ty'],$type))
			{
				return true;
			}
			return false;
		}
		return false;
	 }
	 /**
	 * 导航栏整理
	 */
	 public static function getNavList($admin_id)
	 {
		return self::getTree(self::auth_nav($admin_id), 0);
	 }
	 /**
	 * 左侧导航栏
	 */
	 public static function auth_nav($admin_id)
	 {
		$agid = (new Access())->getAccessArr(['admin_id'=>$admin_id],'agid');
		$rules = (new Group())->groupFieldList($agid,'rules');
		$Rule = new Rule();
		if(in_array('*',$rules))
		{
			$where['nav'] = 1;
			switch(Session::get('admin.admin_type'))
			{
				case 0:$where['ascription'] = 0;break;
				case 1:$where['ascription'] = 1;$where['ty'] = 0;break;
				case 2:$where['ascription'] = 1;break;
				case 3:$where['ascription'] = 2;break;
			}
			return $Rule->ruleList($where,'arid,name,title,param,pid');
		}
		$arid = [];
		foreach($rules as $vo)
		{
			$arid = array_merge($arid,explode(',',$vo));
		}
		$arid = array_unique($arid);
		return $Rule->ruleList(['arid'=>['in',$arid],'nav'=>1],'arid,name,param,title,pid'); 
	 }
	private static function getTree($data, $pId)
	{
		$tree = [];
		foreach($data as $k => $v)
		{
			if(strpos($v['name'], '@') !== false)
			{
				$v['url'] = 1;
			}else{
				$v['url'] = 2;
			}
			if($v['pid'] == $pId)
			{
				if($piddata = self::getTree($data, $v['arid']))
				{
					$v['pid'] = $piddata;
				}
				$tree[] = $v;
			}
		}
		return $tree;
	}
}
